package com.hoow.shakoow.base

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import com.hoow.shakoow.ProjectConfig
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.network.NetworkException
import com.hoow.shakoow.components.dialog.LoadingDialog
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.launch.LaunchActivity
import com.hoow.shakoow.utils.UserStateUtil
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

const val REQ_CODE_PAGE_PERMISSION: Int = 200
const val KEY_PARAMS_VIRTUAL_BANK_NAME: String =
    "KEY_PARAMS_VIRTUAL_BANK_NAME"
const val KEY_PARAMS_VIRTUAL_BANK_ACCOUNT: String =
    "KEY_PARAMS_VIRTUAL_BANK_ACCOUNT"
const val KEY_PARAMS_REPAY_AMOUNT: String =
    "KEY_PARAMS_VIRTUAL_REPAY_AMOUNT"
const val KEY_PARAMS_BACK_ACTION_FINISH: String =
    "KEY_PARAMS_BACK_ACTION_FINISH"
const val KEY_PARAMS_CHAT_QUESTION: String =
    "KEY_PARAMS_CHAT_QUESTION"

const val KEY_PARAMS_IMAGE: String =
    "KEY_PARAMS_IMAGE"
const val KEY_PARAMS_PROMPT: String =
    "KEY_PARAMS_PROMPT"
const val KEY_PARAMS_NEGATIVE_PROMPT: String =
    "KEY_PARAMS_NEGATIVE_PROMPT"

/** key-图片id */
const val KEY_PARAMS_PRODUCT_ID = "PRODUCT_ID"

/** key-图片url */
const val KEY_PARAMS_PRODUCT_IMAGE = "PRODUCT_IMAGE"

abstract class BaseActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_TAG: String = ""

    private lateinit var mLoadingDialog: LoadingDialog
    private var mPermissionList: Array<String>? = null
    private var mPermissionStatement: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ACTIVITY_TAG = this::class.java.simpleName

        with(window) {
//            requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//            exitTransition = Slide(Gravity.START).setDuration(300)
//            enterTransition = Slide(Gravity.END).setDuration(300)
//            exitTransition = Fade()
//            enterTransition = Slide()
        }
        //mFirebaseAnalytics = Firebase.analytics
        setFullScreenMode()
        ACTIVITY_TAG = onBindingViewTag()
        setContentView(onBindingContentView())
//        setContentView(onBindingContentLayoutId())
        mLoadingDialog = LoadingDialog(this)
        setViewModelActions()
        onContentViewBinded()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canHideKeyboard(view, ev)) {
                        hideKeyboard()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
        val gType =
            "${ProjectConfig.Product}_${this.onBindingViewTag()}_START".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    override fun onPause() {
        super.onPause()
        val gType =
            "${ProjectConfig.Product}_${this.onBindingViewTag()}_END".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    open fun savePointEvent(type: String, remark: String = "") {
        try {
            AnalyticsUtil.saveHitPointInfo(
                type = type,
                remark = remark
            )
//            P5bwqcsjj0s2tmsjhwmzg.saveUserBuriedPoint(
//                P2j7zzfx72q29gy4v2nkjja(
//                    type = type,
//                    remark = remark
//                )
//            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**绑定model*/
    protected abstract fun onBindingViewModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onBindingViewTag(): String

    /**绑定视图开始*/
    protected abstract fun onBindingContentView(): View

    /**绑定视图开始*/
//    protected abstract fun onBindingContentLayoutId(): Int

    /**绑定视图完成*/
    protected abstract fun onContentViewBinded()

    private fun setViewModelActions() {
        val viewModelList = onBindingViewModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getLoadingLiveData()
                        .observe(this) { showLoading ->
                            if (showLoading)
                                showLodingDialog()
                            else
                                dismissLoadingDialog()
                        }

                    it.getNetworkExceptionLiveData()
                        .observe(this) {
                            onHandleNetworkExcepton(it)
                        }
                }
            }
        }
    }

    fun showLodingDialog() {
        runOnUiThread {
            mLoadingDialog.showDialog(this)
        }
    }

    fun dismissLoadingDialog() {
        runOnUiThread {
            mLoadingDialog.dismissDialog()
        }
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExcepton(networkException: NetworkException) {
        if (networkException.isAlter()) {
            println("networkException.isAlter()")
            MessageDialog.showDialog(
                supportFragmentManager,
                networkException.msg
            ) {
                if (networkException.code.equals("401", true)) {
                    try {
                        // 清空token
                        UserStateUtil.saveToken("")

                        if (this is LaunchActivity) {
                            this.onRestarLaunch()
                        } else {
                            val intent = baseContext.packageManager.getLaunchIntentForPackage(
                                baseContext.packageName
                            )
                            intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                            startActivity(intent)
                            finish()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        } else {
            Toast.makeText(this, networkException.msg, Toast.LENGTH_LONG)
                .show()
        }
        if (networkException.msg.contains("User does not exist")) {
            //startToNextActivityAndFinish<LoginInputMobileActivity>()
        }
    }

    /**交给子类去实现*/
    open fun onPermissionsRequestAllPass() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mPermissionStatement?.let {
            mPermissionList?.let { list ->
                startEasyPermissions(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mPermissionStatement?.let {
                mPermissionList?.let { list ->
                    startEasyPermissions(it, list)
                }
            }
        }
    }

    @AfterPermissionGranted(REQ_CODE_PAGE_PERMISSION)
    fun onEasyPermissionsAllPass() {
        onPermissionsRequestAllPass()
    }

    open fun requestSpecPermissions(permissionList: Array<String>) {
        try {
            startEasyPermissions(
                getString(R.string.permissions_all),
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected fun startEasyPermissions(
        reqStatement: String,
        permissionList: Array<String>
    ) {
        mPermissionStatement = reqStatement
        mPermissionList = permissionList

        EasyPermissions.requestPermissions(
            this,
            reqStatement,
            REQ_CODE_PAGE_PERMISSION,
            *permissionList
        )
    }

    /**
     * 所有数据是否录入完毕
     */
    open fun isAllFormDataCompleted(): String {
        return ""
    }

    /**
     * 所有数据是否录入完毕
     */
    open fun isAllFormDataFillCompleted(): Boolean {
        return true
    }

}